# Create your views here.
#  _*_ coding: utf-8 _*_
import datetime
from django.contrib.auth import login, authenticate, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.core.serializers import json
from django.db import IntegrityError, Error
from django.http import HttpResponse, Http404
from django.shortcuts import render, redirect, get_object_or_404
from django.template import RequestContext
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import FormView, UpdateView, TemplateView, DetailView
from pytz import timezone
from bbs import helper
from bbs.forms import RegistForm, TopicForm, UserInfoForm
from bbs.helper import save_file
from bbs.models import Message, Board, Topic, Post, User_Info


@login_required
def index_view(request):
    board = Board.objects.all()
    # print(board)
    return render(request,'bbs/index.html',{'board':board})

# def login_view(request):
#     return render(request,'bbs/login.html')

def logout_view(request):
    logout(request)
    return redirect(index_view)

def regist_view(request):
    message = ""
    if request.method == 'POST':
        form = RegistForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            try:
                user = User.objects.create_user(username=username, password=password)

            except IntegrityError as e:
                message = '该用户已经存在！'
                return render(request, 'bbs/regist.html', {'form': form, 'message': message})

            user_auth = authenticate(username=username, password=password)
            if user_auth is not None:
                if user_auth.is_active:
                    login(request, user_auth)
                    r_user = User.objects.get(pk=user.id)
                    i_code = helper.create_id_code(8)
                    userinfo = User_Info(r_user=r_user,i_code=i_code)
                    userinfo.save()
                    return redirect(index_view)
    else:
        form = RegistForm()
    return render(request, 'bbs/regist.html', {'form': form, 'message': message})
@csrf_exempt
def get_user_name(request):
    response = HttpResponse()
    response['Content-Type'] = 'text/javascript'

    result_dict = {}
    if request.method == 'POST':
        username = request.POST['param']
        if len(username) > 0:
            u = User.objects.filter(username=username)
            if u :
                result_dict['info'] = '此用户名已经存在！'
                result_dict['status'] = 'n'
            else:
                result_dict['info'] = '无此用户名可以注册！'
                result_dict['status'] = 'y'
    result_json = json.DjangoJSONEncoder().encode(result_dict)
    response.write(result_json)
    return response
@csrf_exempt
def portrait_upload(request):
    response = HttpResponse()
    response['Content-Type'] = 'text/javascript'

    result_dict = {}
    if request.method == 'POST':
        portrait = request.FILES.get("Filedata",None)
        if portrait:
            r_user = request.user
            userinfo = User_Info.objects.get(r_user=r_user)
            portrait.name = request.user.username+datetime.datetime.now().strftime('%Y%m%d%H%I%S')+portrait.name[-4:]
            userinfo.portrait = portrait
            userinfo.save()
            result_dict['info'] = '上传成功！'
            result_dict['status'] = True
        else:
            result_dict['info'] = '上传失败！'
            result_dict['status'] = False

    result_json = json.DjangoJSONEncoder().encode(result_dict)
    response.write(result_json)
    return response
@csrf_exempt
def userinfo_signature_imgupload(request):
    response = HttpResponse()
    response['Content-Type'] = 'text/javascript'

    result_dict = {}
    if request.method == 'POST':
        buf = request.FILES.get('imgFile',None)

        if buf:
            file_buff = buf.read()
            file_name = request.user.username+datetime.datetime.now().strftime('%Y%m%d%H%I%S')+buf.name[-4:]
            print file_name
            try:
                save_file('/signature_uploadfile/',file_name,file_buff)
                result_dict['error'] = 0
                result_dict['url'] = '/media/signature_uploadfile/'+file_name
            except Exception,e:
                result_dict['error'] = 1

        else:
            result_dict['error'] = 1
            print 'no this file!'

    result_json = json.DjangoJSONEncoder().encode(result_dict)
    response.write(result_json)
    return response


@login_required
def message_list_view(request):
    message_list = Message.objects.filter(message_to=request.user)
    return render(request,'bbs/message_list.html',{'message_list':message_list})

@login_required
def message_edit_view(request):
    return render(request,'bbs/message_edit.html')

@login_required
def movie_show_view(request):
    return render(request,'bbs/movie_show.html')

@login_required
def userinfo_view(request):
    userinfo = get_object_or_404(User_Info,r_user=request.user)
    if request.method == 'POST':
        form = UserInfoForm(request.POST)
        if form.is_valid():
            form = UserInfoForm(request.POST,request.FILES,instance=userinfo)
            form.save()
        else:
           return render(request,'bbs/500.html',{'errors':form.errors})
    else:

        form = UserInfoForm(instance=userinfo)
    return render(request, 'bbs/userinfo.html',{'form':form,'ud':userinfo})


@login_required
def topic_create_view(request):
    if request.method == 'POST':
        form = TopicForm(request.POST)
        if form.is_valid():
            # user_id = request.user.id
            topic_publisher = request.user
            topic_title = form.cleaned_data.get('topic_title')
            topic_content = form.cleaned_data.get('topic_content')
            # topic_board = Board.objects.get(pk=form.cleaned_data.get('topic_board'))
            topic_board = form.cleaned_data.get('topic_board')
            topic = Topic(topic_title=topic_title,topic_content=topic_content,topic_publisher=topic_publisher,topic_board=topic_board)
            topic.save()
            board = Board.objects.get(pk=topic_board.id)
            board.board_total_topic += 1
            board.save()
            return redirect(index_view)
        else:
            return render(request,'bbs/500.html',{'errors':form.errors})
    else:
         form = TopicForm()
    return  render(request, 'bbs/topic_create.html',{'form':form})



@login_required
def topic_list_view(request,pk):
    if request.method == 'GET':
        board = Board.objects.get(pk=pk)
        topic_list = Topic.objects.filter(topic_board=board)
        paginator = Paginator(topic_list,10)
        page = request.GET.get('page')
        try:
            topics = paginator.page(page)
        except PageNotAnInteger:
            topics = paginator.page(1)
        except EmptyPage:
            topics = paginator.page(paginator.num_pages)

        board_list = Board.objects.all()
        return render(request,'bbs/topic_list.html',{'topics':topics,'boards':board_list})
    # return render(request,'bbs/topic_list.html')

@login_required
def topic_show_view(request,pk):
    if request.method == 'GET':
        topic = Topic.objects.get(pk=pk)
        posts = Post.objects.filter(post_topic=topic)
    return render(request,'bbs/topic_show.html',{'topic':topic,'posts':posts})
